package com.easy.activiti.listener;

import org.activiti.engine.delegate.event.ActivitiEvent;
import org.springframework.util.Assert;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author zhouchuang
 * 2024-11-05 10:47:11
 */
public interface EventHandler {
    void handle(ActivitiEvent event);
    default EventServerExcuter getActuator(String key){
        return Context.get(key);
    }
    class Context{
        private static Map<String, EventServerExcuter> activitiServerBeanMap = new HashMap<>();
        public static void register(String key,Object bean, Method method){
            Assert.isTrue(!activitiServerBeanMap.containsKey(key),String.format("key[%s]重复,一个流程只能对应一个监听",key));
            activitiServerBeanMap.put(key,new EventServerExcuter(bean,method));
        };
        public static EventServerExcuter get(String key){
            return Optional.ofNullable(activitiServerBeanMap.get(key)).orElse(new EventServerExcuter());
        }
    }
    class EventServerExcuter {
        private Object bean;
        private Method method;

        public EventServerExcuter(){

        }

        public EventServerExcuter(Object bean , Method method) {
            this.bean = bean;
            this.method  = method;
        }

        public Object execute(Object obj){
            try {
                if(method!=null&&bean!=null){
                    return method.invoke(bean,obj);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return null;
        }
        public Object execute(){
            try {
                if(method!=null&&bean!=null){
                    return method.invoke(bean);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return null;
        }
    }
}